package com.chinda.common.security.handler;

import com.chinda.common.enums.MessageEnum;
import com.chinda.common.utils.R;
import com.chinda.common.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录失败处理类
 *
 * @author Wang Chinda
 * @date 2020/7/11
 * @see
 * @since 1.0
 */
@Slf4j
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {

    /**
     * 登陆失败返回
     * @param request
     * @param response
     * @param exception
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {
        // 这些对于操作的处理类可以根据不同异常进行不同处理
        if (exception instanceof UsernameNotFoundException) {
            log.info(MessageEnum.SYS_SECURITY_0011.getMsg(), exception);
            ResponseUtil.outJson(response, R.error(MessageEnum.SYS_SECURITY_0011.getMsg()));
            return;
        }

        if (exception instanceof LockedException) {
            log.info(MessageEnum.SYS_SECURITY_0009.getMsg(), exception);
            ResponseUtil.outJson(response, R.error(MessageEnum.SYS_SECURITY_0009.getMsg()));
            return;
        }

        if (exception instanceof BadCredentialsException) {
            log.info(MessageEnum.SYS_SECURITY_0010.getMsg(), exception);
            ResponseUtil.outJson(response, R.error(MessageEnum.SYS_SECURITY_0010.getMsg()));
            return;
        }

        if (exception instanceof AccountExpiredException) {
            log.info(MessageEnum.SYS_SECURITY_0013.getMsg(), exception);
            ResponseUtil.outJson(response, R.error(MessageEnum.SYS_SECURITY_0013.getMsg()));
            return;
        }

        if (exception instanceof DisabledException) {
            log.info(MessageEnum.SYS_SECURITY_0014.getMsg(), exception);
            ResponseUtil.outJson(response, R.error(MessageEnum.SYS_SECURITY_0014.getMsg()));
            return;
        }
        if (exception instanceof CredentialsExpiredException) {
            log.info(MessageEnum.SYS_SECURITY_0015.getMsg(), exception);
            ResponseUtil.outJson(response, R.error(MessageEnum.SYS_SECURITY_0015.getMsg()));
            return;
        }

        log.info(MessageEnum.SYS_SECURITY_0002.getMsg(), exception);
        ResponseUtil.outJson(response, R.error());
    }
}
